<template>
  <el-form :model="blogInfo" ref="formRef" label-width="120px" class="blog-form" :rules="formRules">
    <!-- 第一行：下拉框和两个选择器 -->

    <el-form-item label="发布类型" class="form-item" prop="blogSortUid">
      <el-select v-model="blogInfo.blogSortUid" placeholder="请选择类型">
        <el-option v-for="button in allButtons" :key="button.uid" :label="button.sortName" :value="button.uid">
        </el-option>
      </el-select>
    </el-form-item>


    <el-form-item label="云标签" class="form-item" prop="tags">
      <el-select v-model="blogInfo.tags" multiple placeholder="请选择标签">
        <el-option v-for="tag in hotTagData" :key="tag.uid" :label="tag.content" :value="tag.uid">
        </el-option>
      </el-select>
    </el-form-item>

    <div class="form-item-row">
      <el-form-item label="是否公开" class="form-item" prop="isPublish">
        <el-switch v-model="blogInfo.isPublish" active-text="是" inactive-text="否"></el-switch>
      </el-form-item>

      <el-form-item label="是否打开评论" class="form-item" prop="openComment">
        <el-switch v-model="blogInfo.openComment" active-text="是" inactive-text="否"></el-switch>
      </el-form-item>

    </div>

    <el-form-item label="标题" prop="title">
      <el-input type="textarea" v-model="blogInfo.title" :rows="1" placeholder="请输入标题内容">
      </el-input>
    </el-form-item>

    <el-form-item label="总结" prop="summary">
      <el-input type="textarea" v-model="blogInfo.summary" :rows="1" placeholder="请输入总结内容">
      </el-input>
    </el-form-item>

    <!-- 第二行：文本输入框 -->
    <el-form-item label="内容" prop="content">
      <el-input type="textarea" v-model="blogInfo.content" :rows="10" placeholder="请输入文字内容">
      </el-input>
    </el-form-item>

    <el-form-item v-for="gridIndex in Math.max(1, Math.ceil(photoList.length / 9))" :key="gridIndex">
      <div class="imgGrid">
        <!-- Loop through the photos for the current grid -->
        <div v-for="(photo, index) in photoList.slice((gridIndex - 1) * 9, gridIndex * 9)" :key="index" class="imgBody"
          @mouseover="icon = true" @mouseout="icon = false">
          <i class="el-icon-error inputClass" v-show="icon" @click="deletePhoto((gridIndex - 1) * 9 + index)"></i>
          <img :src="photo" />
        </div>
        <!-- Show add photo button if there's room for more photos -->
        <div v-if="photoList.length < gridIndex * 9" class="uploadImgBody" @click="checkPhoto">
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </div>
      </div>
    </el-form-item>

    <el-form-item class="button-container">
      <el-button class="large-button" type="primary" @click="handleSubmit">提交</el-button>
    </el-form-item>

    <!--    <div v-else class="uploadImgBody" @click="checkPhoto">
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </div> -->


    <avatar-cropper v-show="imagecropperShow" :ki="imagecropperKey" :width="300" :height="300" :url="url" lang-type="zh"
      @close="close" @crop-upload-success="cropSuccess" />


  </el-form>
</template>

<script>
  import {
    addBlog
  } from '@/api/webBlog'
  import AvatarCropper from '@/components/AvatarCropper'
  export default {
    components: {
      AvatarCropper
    },
    props: {
      hotTagData: {
        type: Array,
        default: () => []
      },
      allButtons: {
        type: Array,
        default: () => [{
          sortName: '全部',
          uid: 0
        }]
      }
    },
    created() {
      if (this.allButtons.length >= 1) {
        this.allButtons.shift();
      }

    },
    data() {
      return {
        formRules: {
          blogSortUid: [{
            required: true,
            message: '请选择发布类型',
            trigger: 'change'
          }],
          tags: [{
            required: true,
            message: '请选择云标签',
            trigger: 'change'
          }],
          title: [{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }],
          summary: [{
            required: true,
            message: '请输入总结',
            trigger: 'blur'
          }],
          content: [{
            required: true,
            message: '请输入内容',
            trigger: 'blur'
          }],
        },
        icon: false,
        avatar: [],
        photoList: [],
        pictureCnt: 9, // 你希望显示的图片上传区域数量
        imagecropperShow: false,
        imagecropperKey: 0,
        url: process.env.PICTURE_API + "/file/cropperPicture",
        blogInfo: {
          articlesPart: "",
          author: "",
          blogSortUid: "",
          content: "",
          fileUid: "",
          isOriginal: "1",
          tags: [],
          isPublish: "1",
          openComment: "1",
          summary: "",
          tagUid: "",
          title: "",
          type: "0",
          uid: null
        }
      };
    },
    methods: {
      handleSubmit() {
        // console.log(this.$store.state.user.isLogin);
        // console.log(this.$store.state.user.userInfo);

        this.$refs.formRef.validate((valid) => {
          if (valid) {
            this.blogInfo.author = this.$store.state.user.userInfo.userName;
            this.blogInfo.articlesPart = "个人上传";
            this.blogInfo.isPublish = this.blogInfo.isPublish ? 1 : 0;
            this.blogInfo.openComment = this.blogInfo.openComment ? 1 : 0;
            // 处理标签
            this.blogInfo.tagUid = this.blogInfo.tags.join(',');

            // 处理文件
            this.blogInfo.fileUid = this.avatar.join(',');
            // console.log(this.blogInfo)
            // 调用 API 提交数据
            addBlog(this.blogInfo).then(response => {
              if (response.code === this.$ECode.SUCCESS) {
                // 显示成功提示
                window.location.reload()

                this.$message.success('博客发布成功！');
              } else {
                // 显示失败提示
                this.$message.error('博客发布失败，请重试。');
              }
            }).catch(error => {
              // 处理网络错误
              this.$message.error('提交请求失败，请检查网络。');
            });
          } else {
            // 如果表单验证失败，显示提示信息
            this.$message.error('请填写所有必填项。');
          }
        });
      },

      deletePhoto(index) {
        // 从 photoList 中删除指定索引的图片
        if (index >= 0 && index < this.photoList.length) {
          this.photoList.splice(index, 1);
        }

        // 从 avatar 中删除指定索引的图片
        if (index >= 0 && index < this.avatar.length) {
          this.avatar.splice(index, 1);
        }

        console.log(this.photoList);
        console.log(this.avatar);

        this.icon = false;
      },

      checkPhoto() {
        this.imagecropperShow = true
      },

      cropSuccess(resData) {
        if (this.photoList.length >= 8) {
          this.imagecropperShow = false
        }
        this.imagecropperKey = this.imagecropperKey + 1
        // 判断当前激活的页面
        // 激活个人中心页面

        this.photoList.push(resData[0].url)
        this.avatar.push(resData[0].uid)
        console.log(this.photoList)
        console.log(this.avatar)
        console.log(this.$store.state.user)
      },
      close() {
        this.imagecropperShow = false
      },
      addImage() {
        // 这里可以实现插入图片的逻辑，比如弹出图片选择器或上传图片
        alert('插入图片功能待实现');
      },
      submitForm() {
        console.log('提交表单:', this.form);
        // 提交表单的逻辑
      },
      resetForm() {
        this.$refs.formRef.resetFields();
      }
    }
  };
</script>

<style scoped>
  .large-button {
    font-size: 18px;
    /* 调整字体大小 */
    padding: 12px 50px;
    /* 调整内边距 */
  }

  .button-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    /* Optional: add some spacing from the form items above */
  }


  .imgGrid {
    display: flex;
    flex-wrap: wrap;
  }


  .inputClass {
    position: absolute;
  }

  .imgBody {
    width: calc(33.33% - 10px);
    /* 宽度设置为三分之一减去间距 */
    width: 100px;
    height: 100px;
    border: solid 2px #ffffff;
    float: left;
    position: relative;
  }

  .imgBody img {
    width: 100px;
    height: 100px;
  }



  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .uploadImgBody {
    margin-left: 5px;
    width: 100px;
    height: 100px;
    border: dashed 1px #c0c0c0;
    float: left;
    position: relative;
  }

  .uploadImgBody :hover {
    border: dashed 1px #00ccff;
  }


  .blog-form {
    padding-right: 80px;
    max-width: auto;
  }

  .form-item-row {
    display: flex;
    gap: 16px;
    /* 调整项之间的间隔 */
  }

  .form-item {
    flex: 1;
    /* 让所有的 form-item 等宽 */
  }

  @media (max-width: 768px) {
    .blog-form {

      padding: 15px;
      /* 增加内边距以适应小屏幕 */
      max-width: 100%;
      box-sizing: border-box;
      margin-left: -40px;
      /* 确保 padding 不超出屏幕 */
    }

    .form-item-row {
      flex-direction: column;
      /* 在移动端上垂直排列 */
      gap: 10px;
      /* 添加间距 */
    }

    .form-item {
      flex: 1 1 auto;
      /* 使表单项适应其内容 */
      margin-bottom: 10px;
      /* 增加底部间距 */
    }

    .imgGrid {
      flex-direction: column;
      /* 图片网格垂直排列 */
      gap: 10px;
      /* 添加间距 */
    }

    .imgBody,
    .uploadImgBody {
      width: 100%;
      /* 使图片和上传区域占满整个宽度 */
      height: auto;
      /* 自动调整高度以保持比例 */
    }

    .imgBody img {
      width: 100%;
      /* 使图片宽度适应父容器 */
      height: auto;
      /* 保持图片比例 */
    }

    .avatar-uploader-icon {
      font-size: 24px;
      /* 调整图标大小 */
      width: 100%;
      /* 使图标区域占满宽度 */
      height: auto;
      /* 自动调整高度 */
      line-height: normal;
      /* 调整行高以适应小屏幕 */
    }

    .button-container {
      text-align: center;
      /* 使按钮居中 */
      margin-top: 20px;
      /* 保持顶部间距 */
    }

    .large-button {
      font-size: 16px;
      /* 调整按钮字体大小 */
      padding: 10px 20px;
      /* 调整按钮内边距 */
    }
  }
</style>
